<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="货主编码" prop="ownerCode">
        <el-input
          v-model="queryParams.ownerCode"
          placeholder="请输入货主编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="货主名称" prop="ownerName">
        <el-input
          v-model="queryParams.ownerName"
          placeholder="请输入货主名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="货主类型" prop="ownerType">
        <el-select v-model="queryParams.ownerType" placeholder="请选择货主类型" clearable>
          <el-option
            v-for="dict in dict.type.wms_owner_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['wms:cargoOwner:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wms:cargoOwner:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wms:cargoOwner:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['wms:cargoOwner:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="cargoOwnerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="货主编码" align="center" prop="ownerCode" />
      <el-table-column label="货主名称" align="center" prop="ownerName" />
      <el-table-column label="货主类型" align="center" prop="ownerType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.wms_owner_type" :value="scope.row.ownerType"/>
        </template>
      </el-table-column>
      <el-table-column label="联系人" align="center" prop="contactPerson" />
      <el-table-column label="联系电话" align="center" prop="contactPhone" />
      <el-table-column label="邮箱" align="center" prop="email" />
      <el-table-column label="地址" align="center" prop="address" show-overflow-tooltip />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wms:cargoOwner:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-setting"
            @click="handleOrderNumberConfig(scope.row)"
            v-hasPermi="['wms:cargoOwner:query']"
          >单号配置</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wms:cargoOwner:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改货主信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="货主编码" prop="ownerCode">
              <el-input v-model="form.ownerCode" placeholder="请输入货主编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="货主名称" prop="ownerName">
              <el-input v-model="form.ownerName" placeholder="请输入货主名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="货主类型" prop="ownerType">
              <el-select v-model="form.ownerType" placeholder="请选择货主类型" style="width: 100%">
                <el-option
                  v-for="dict in dict.type.wms_owner_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactPerson">
              <el-input v-model="form.contactPerson" placeholder="请输入联系人" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入地址" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="信用等级" prop="creditLevel">
              <el-select v-model="form.creditLevel" placeholder="请选择信用等级" style="width: 100%">
                <el-option label="AAA级" :value="1" />
                <el-option label="AA级" :value="2" />
                <el-option label="A级" :value="3" />
                <el-option label="B级" :value="4" />
                <el-option label="C级" :value="5" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 单号配置对话框 -->
    <el-dialog title="单号配置" :visible.sync="orderNumberConfigOpen" width="1000px" append-to-body>
      <div class="mb8">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAddOrderNumberRule"
        >新增规则</el-button>
      </div>
      
      <el-table v-loading="orderNumberRuleLoading" :data="orderNumberRuleList">
        <el-table-column label="订单类型" align="center" prop="orderType">
          <template slot-scope="scope">
            <span v-if="scope.row.orderType === 'INBOUND'">入库单</span>
            <span v-else-if="scope.row.orderType === 'OUTBOUND'">出库单</span>
            <span v-else-if="scope.row.orderType === 'TRANSFER'">移库单</span>
            <span v-else-if="scope.row.orderType === 'INVENTORY'">盘点单</span>
            <span v-else>{{ scope.row.orderType }}</span>
          </template>
        </el-table-column>
        <el-table-column label="规则名称" align="center" prop="ruleName" />
        <el-table-column label="编号前缀" align="center" prop="prefix" />
        <el-table-column label="日期格式" align="center" prop="dateFormat" />
        <el-table-column label="流水号长度" align="center" prop="serialLength" />
        <el-table-column label="分隔符" align="center" prop="division" />
        <el-table-column label="状态" align="center" prop="enabled">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.enabled === 1" type="success">启用</el-tag>
            <el-tag v-else type="danger">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="预览" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handlePreviewOrderNumber(scope.row)">预览格式</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdateOrderNumberRule(scope.row)"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDeleteOrderNumberRule(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="orderNumberConfigOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改订单编号规则对话框 -->
    <el-dialog :title="orderNumberRuleTitle" :visible.sync="orderNumberRuleOpen" width="600px" append-to-body>
      <el-form ref="orderNumberRuleForm" :model="orderNumberRuleForm" :rules="orderNumberRuleRules" label-width="120px">
        <el-form-item label="订单类型" prop="orderType">
          <el-select v-model="orderNumberRuleForm.orderType" placeholder="请选择订单类型">
            <el-option label="入库单" value="INBOUND" />
            <el-option label="出库单" value="OUTBOUND" />
            <el-option label="移库单" value="TRANSFER" />
            <el-option label="盘点单" value="INVENTORY" />
          </el-select>
        </el-form-item>
        <el-form-item label="规则名称" prop="ruleName">
          <el-input v-model="orderNumberRuleForm.ruleName" placeholder="请输入规则名称" />
        </el-form-item>
        <el-form-item label="编号前缀" prop="prefix">
          <el-input v-model="orderNumberRuleForm.prefix" placeholder="请输入编号前缀" />
        </el-form-item>
        <el-form-item label="编号后缀" prop="suffix">
          <el-input v-model="orderNumberRuleForm.suffix" placeholder="请输入编号后缀" />
        </el-form-item>
        <el-form-item label="日期格式" prop="dateFormat">
          <el-select v-model="orderNumberRuleForm.dateFormat" placeholder="请选择日期格式">
            <el-option label="yyyyMMdd" value="yyyyMMdd" />
            <el-option label="yyyy-MM-dd" value="yyyy-MM-dd" />
            <el-option label="yyMMdd" value="yyMMdd" />
            <el-option label="MMdd" value="MMdd" />
          </el-select>
        </el-form-item>
        <el-form-item label="流水号长度" prop="serialLength">
          <el-input-number v-model="orderNumberRuleForm.serialLength" :min="1" :max="10" placeholder="请输入流水号长度" />
        </el-form-item>
        <el-form-item label="流水号起始值" prop="serialStart">
          <el-input-number v-model="orderNumberRuleForm.serialStart" :min="1" placeholder="请输入流水号起始值" />
        </el-form-item>
        <el-form-item label="分隔符" prop="division">
          <el-select v-model="orderNumberRuleForm.division" placeholder="请选择分隔符">
            <el-option label="无" value="" />
            <el-option label="-" value="-" />
            <el-option label="_" value="_" />
            <el-option label="." value="." />
          </el-select>
        </el-form-item>
        <el-form-item label="是否启用" prop="enabled">
          <el-radio-group v-model="orderNumberRuleForm.enabled">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="orderNumberRuleForm.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="预览">
          <el-input v-model="orderNumberRulePreview" readonly placeholder="编号预览" />
          <el-button type="text" @click="handlePreviewOrderNumberForm">刷新预览</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitOrderNumberRuleForm">确 定</el-button>
        <el-button @click="cancelOrderNumberRule">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCargoOwner, getCargoOwner, delCargoOwner, addCargoOwner, updateCargoOwner } from "@/api/wms/cargoOwner";
import { listOrderNumberRuleByOwnerId, addOrderNumberRule, updateOrderNumberRule, delOrderNumberRule, previewOrderNumber } from "@/api/wms/orderNumberRule";

export default {
  name: "CargoOwner",
  dicts: ['wms_owner_type', 'sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 货主信息表格数据
      cargoOwnerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 单号配置对话框
      orderNumberConfigOpen: false,
      orderNumberRuleOpen: false,
      orderNumberRuleTitle: "",
      orderNumberRuleLoading: false,
      orderNumberRuleList: [],
      orderNumberRulePreview: "",
      currentOwnerId: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ownerCode: null,
        ownerName: null,
        ownerType: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        ownerCode: [
          { required: true, message: "货主编码不能为空", trigger: "blur" }
        ],
        ownerName: [
          { required: true, message: "货主名称不能为空", trigger: "blur" }
        ],
        ownerType: [
          { required: true, message: "货主类型不能为空", trigger: "change" }
        ],
        contactPhone: [
          { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ]
      },
      // 订单编号规则表单参数
      orderNumberRuleForm: {},
      // 订单编号规则表单校验
      orderNumberRuleRules: {
        orderType: [
          { required: true, message: "订单类型不能为空", trigger: "change" }
        ],
        ruleName: [
          { required: true, message: "规则名称不能为空", trigger: "blur" }
        ],
        serialLength: [
          { required: true, message: "流水号长度不能为空", trigger: "blur" }
        ],
        serialStart: [
          { required: true, message: "流水号起始值不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询货主信息列表 */
    getList() {
      this.loading = true;
      listCargoOwner(this.queryParams).then(response => {
        this.cargoOwnerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        ownerCode: null,
        ownerName: null,
        ownerType: null,
        contactPerson: null,
        contactPhone: null,
        email: null,
        address: null,
        creditLevel: null,
        status: 0,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加货主信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCargoOwner(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改货主信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCargoOwner(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCargoOwner(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除货主信息编号为"' + ids + '"的数据项？').then(function() {
        return delCargoOwner(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('wms/cargoOwner/export', {
        ...this.queryParams
      }, `cargoOwner_${new Date().getTime()}.xlsx`)
    },
    /** 单号配置按钮操作 */
    handleOrderNumberConfig(row) {
      this.currentOwnerId = row.id;
      this.orderNumberConfigOpen = true;
      this.getOrderNumberRuleList();
    },
    /** 查询订单编号规则列表 */
    getOrderNumberRuleList() {
      this.orderNumberRuleLoading = true;
      listOrderNumberRuleByOwnerId(this.currentOwnerId).then(response => {
        this.orderNumberRuleList = response.data;
        this.orderNumberRuleLoading = false;
      });
    },
    /** 新增订单编号规则 */
    handleAddOrderNumberRule() {
      this.resetOrderNumberRuleForm();
      this.orderNumberRuleOpen = true;
      this.orderNumberRuleTitle = "添加订单编号规则";
    },
    /** 修改订单编号规则 */
    handleUpdateOrderNumberRule(row) {
      this.resetOrderNumberRuleForm();
      this.orderNumberRuleForm = { ...row };
      this.orderNumberRuleOpen = true;
      this.orderNumberRuleTitle = "修改订单编号规则";
      this.handlePreviewOrderNumberForm();
    },
    /** 删除订单编号规则 */
    handleDeleteOrderNumberRule(row) {
      this.$modal.confirm('是否确认删除该订单编号规则？').then(function() {
        return delOrderNumberRule(row.ruleId);
      }).then(() => {
        this.getOrderNumberRuleList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 预览订单编号 */
    handlePreviewOrderNumber(row) {
      previewOrderNumber(row).then(response => {
        this.$modal.msgSuccess("预览编号：" + response.data);
      });
    },
    /** 表单预览订单编号 */
    handlePreviewOrderNumberForm() {
      if (this.orderNumberRuleForm.ruleName) {
        previewOrderNumber(this.orderNumberRuleForm).then(response => {
          this.orderNumberRulePreview = response.data;
        }).catch(() => {
          this.orderNumberRulePreview = "预览失败";
        });
      }
    },
    /** 重置订单编号规则表单 */
    resetOrderNumberRuleForm() {
      this.orderNumberRuleForm = {
        ruleId: null,
        ownerId: this.currentOwnerId,
        orderType: null,
        ruleName: null,
        prefix: null,
        suffix: null,
        dateFormat: "yyyyMMdd",
        serialLength: 4,
        serialStart: 1,
        division: "-",
        enabled: 1,
        remark: null
      };
      this.orderNumberRulePreview = "";
      this.resetForm("orderNumberRuleForm");
    },
    /** 取消订单编号规则 */
    cancelOrderNumberRule() {
      this.orderNumberRuleOpen = false;
      this.resetOrderNumberRuleForm();
    },
    /** 提交订单编号规则表单 */
    submitOrderNumberRuleForm() {
      this.$refs["orderNumberRuleForm"].validate(valid => {
        if (valid) {
          if (this.orderNumberRuleForm.ruleId != null) {
            updateOrderNumberRule(this.orderNumberRuleForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.orderNumberRuleOpen = false;
              this.getOrderNumberRuleList();
            });
          } else {
            addOrderNumberRule(this.orderNumberRuleForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.orderNumberRuleOpen = false;
              this.getOrderNumberRuleList();
            });
          }
        }
      });
    }
  },
  watch: {
    'orderNumberRuleForm.prefix': 'handlePreviewOrderNumberForm',
    'orderNumberRuleForm.suffix': 'handlePreviewOrderNumberForm',
    'orderNumberRuleForm.dateFormat': 'handlePreviewOrderNumberForm',
    'orderNumberRuleForm.serialLength': 'handlePreviewOrderNumberForm',
    'orderNumberRuleForm.serialStart': 'handlePreviewOrderNumberForm',
    'orderNumberRuleForm.division': 'handlePreviewOrderNumberForm'
  }
};
</script>